package com.hong.serviceorder.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.hong.model.enums.PaymentTypeEnum;
import com.hong.model.enums.RefundStatusEnum;
import com.hong.model.model.order.OrderInfo;
import com.hong.model.model.order.PaymentInfo;
import com.hong.model.model.order.RefundInfo;
import com.hong.serviceorder.mapper.OrderMapper;
import com.hong.serviceorder.service.OrderService;
import com.hong.serviceorder.service.PaymentService;
import com.hong.serviceorder.service.RefundInfoService;
import com.hong.serviceorder.service.WeiXinService;
import com.hong.serviceorder.utils.ConstantPropertiesUtils;
import com.hong.serviceorder.utils.HttpClient;
import com.hong.serviceorder.utils.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WeiXinServiceImpl implements WeiXinService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RefundInfoService refundInfoService;
    @Autowired
    private RestTemplate restTemplate;
    //生成微信支付二维码
    @Transactional
    @Override
    public Map createNative(Long orderId) {
        BasicHttpClientConnectionManager connManager=null;
        try {
            //从redis获取数据(防止重复生成支付码？)
            Map payMap  = (Map) redisTemplate.opsForValue().get(orderId.toString());
            if(payMap !=null){
                return payMap;
            }

            //1. 根据orderId获取订单信息
            OrderInfo order = orderService.getById(orderId);
            //2. 向支付记录表里添加信息  第二个参数为支付类型
            paymentService.savePaymentInfo(order, PaymentTypeEnum.WEIXIN.getStatus());

            //3. 设置参数，调用微信生成二维码接口
            //把参数转换成xml格式，使用商户key进行加密
            Map paramMap = new HashMap<>();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            String body = order.getReserveDate() + "就诊"+ order.getDepname();
            paramMap.put("body", body);
            paramMap.put("out_trade_no", order.getOutTradeNo());
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1"); //测试金额
            paramMap.put("spbill_create_ip", "127.0.0.1");
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            paramMap.put("trade_type", "NATIVE");  //支付类型为扫描
            //2、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClientBuilder("https://api.mch.weixin.qq.com/pay/unifiedorder")
                    .setHttps(true)
                    .setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY))
                    .build();
            client.post();
            //返回相关数据
            String xml = client.getContent();
            //转换成map
            Map<String, String>  resultMap = WXPayUtil.xmlToMap(xml);


//            connManager = new BasicHttpClientConnectionManager(
//                    RegistryBuilder.<ConnectionSocketFactory>create()
//                            .register("http", PlainConnectionSocketFactory.getSocketFactory())
//                            .register("https", SSLConnectionSocketFactory.getSocketFactory())
//                            .build(),
//                    null,
//                    null,
//                    null
//            );
//            CloseableHttpClient httpClient =  HttpClientBuilder.create()
//                    .setConnectionManager(connManager)
//                    .build();
//            String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//            HttpPost httpPost = new HttpPost(url);
//
//            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
//            httpPost.setConfig(requestConfig);
//
//            StringEntity postEntity = new StringEntity(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY), "UTF-8");
//            httpPost.addHeader("Content-Type", "text/xml");
////            httpPost.addHeader("User-Agent", USER_AGENT + " " + config.getMchID());
//            httpPost.setEntity(postEntity);
//
//            HttpResponse httpResponse = httpClient.execute(httpPost);
//            HttpEntity httpEntity = httpResponse.getEntity();
//            Map<String, String>  resultMap = WXPayUtil.xmlToMap(EntityUtils.toString(httpEntity, "UTF-8"));
//            System.out.println("resultMap :" + resultMap);
            //封装并返回结果
            Map map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", order.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url")); //二维码地址

            //存到redis
            if(resultMap.get("result_code")!=null){
                redisTemplate.opsForValue().set(orderId.toString(), map, 120 , TimeUnit.MINUTES);
            }
            return map;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            if(connManager!=null){
                connManager.close();
            }
        }
    }

    @Override
    public Map<String, String> queryPayStatus(Long orderId) {
        try {
            //根据id获取订单信息
            OrderInfo orderInfo = orderService.getById(orderId);
            //封装请求参数
            Map paramMap=new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);  //微信支付id
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);    //商户号
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());    //订单编号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());    //随机字符串
            //设置请求内容
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            //得到微信接口返回的数据
            String xmlParam = client.getXmlParam();
            Map<String, String> result=WXPayUtil.xmlToMap(xmlParam);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 根据订单id 进行微信退款操作
     * @param orderId
     * @return
     */
    @Override
    public Boolean refund(Long orderId) {
        try {
            //获取支付记录信息
            PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());
            //添加信息到退款记录表
            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
            //判断当前订单数据是否已经退款
            if(refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()){
                //以成功退款
                return true;
            }
            //调用微信接口实现退款(因为微信付款有问题所以不做退款操作)
            //封装需要的参数
            Map<String,String> paramMap = new HashMap<>();
            paramMap.put("appid",ConstantPropertiesUtils.APPID);       //公众账号ID
            paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);   //商户编号
            paramMap.put("nonce_str",WXPayUtil.generateNonceStr());    //随机码
            paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no","tk" +paymentInfo.getOutTradeNo()); //商户退款单号
            //生成环境退款金额决定于挂号金额，这里测试使用0.01
//            paramMap.put("total_fee",paymentInfo.getTotalAmount().multiply(new BigDecimal("0.01")).longValue()+"");
//            paramMap.put("refund_fee",paymentInfo.getTotalAmount().multiply(new BigDecimal("0.01")).longValue()+"");
            paramMap.put("total_fee","1");
            paramMap.put("refund_fee","1");
            String paramXml = WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY);

            //设置接口内容
            HttpClient client =new HttpClientBuilder("https://api.mch.weixin.qq.com/secapi/pay/refund")
            .setHttps(true).setXmlParam(paramXml).setCert(true).setCertPassword(ConstantPropertiesUtils.PARTNER).build();
            client.post();

            //接收返回数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
//            Map<String, String> resultMap=new HashMap<>();
            resultMap.put("result_code",WXPayConstants.SUCCESS);
            if(null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))){
                //返回成功，设置refundInfo 存入退款记录表
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            //退款失败
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
